import { RechargeOrder } from '@app/db/entities/RechargeOrder';
import { Body, Controller, Post, Req } from '@nestjs/common';
import { BaseController } from '../base/base.controller';
import { DbService } from '@app/db';
import { FindOptionsWhere, In } from 'typeorm';
import { PageDto } from './dto';
import { User } from '@app/db/entities/User';

@Controller('rechargeOrder')
export class RechargeOrderController  extends BaseController {
    constructor(
        private readonly db:DbService
    ){
        super()
    }

    @Post('page')
    async page(@Body() dto:PageDto, @Req() { locale }) {
       
        let result:PaginationResult<RechargeOrder & {user? : User}> = {
            total : 0,
            rows : []
        }

        let where:FindOptionsWhere<RechargeOrder> = {
            
        }

        
        if(dto.orderNo) {
            where.orderNo = dto.orderNo
        }

        result.total = await this.db.rechargeOrder.count(where)

        if(result.total > 0) {
            result.rows = await this.db.rechargeOrder.pagination(dto.pageNo, dto.pageSize, where, null, {id : 'DESC'})
            
            if(result.rows.length > 0) {
                const userIds:number[] = []
                const userMap:{[key:string]:User} = {}


                result.rows.forEach(row => {
                    if(!userIds.includes(row.userId)) {
                        userIds.push(row.userId)
                    }
                })

                let users = await this.db.user.find({id : userIds.length == 0 ? userIds[0] : In(userIds)}, ['id', 'nickname', 'avatar'])
                users.forEach(user => {
                    userMap[user.id] = user
                })
                users = null

                result.rows.forEach(row => {
                    row.user = userMap[row.userId]
                })
            }
        
        }
        

        return this.successRes(result)

    }
}
